"use client";

import React, { useState, useEffect } from "react";
import { Plus } from "lucide-react";
import { HealthService, type HealthRecord } from "@/services/health.service";
import { AuthGuard } from "@/components/auth/auth-guard";
import { HealthStats } from "@/components/health/HealthStats";
import { HealthRecordList } from "@/components/health/HealthRecordList";
import { HealthRecordForm } from "@/components/health/HealthRecordForm";
import { HealthTips } from "@/components/health/HealthTips";
import { HealthTrends } from "@/components/health/HealthTrends";

export default function HealthPage() {
  const [records, setRecords] = useState<HealthRecord[]>([]);
  const [latestRecords, setLatestRecords] = useState<{
    weight?: HealthRecord;
    bloodPressure?: HealthRecord;
    heartRate?: HealthRecord;
    sleepQuality?: HealthRecord;
  }>({});
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [isCreating, setIsCreating] = useState(false);
  const [editingRecord, setEditingRecord] = useState<HealthRecord | null>(null);
  const [modalError, setModalError] = useState("");
  const [activeChart, setActiveChart] = useState("heartRate");

  useEffect(() => {
    fetchHealthRecords();
  }, []);

  async function fetchHealthRecords() {
    try {
      setIsLoading(true);
      const response = await HealthService.getRecords({});
      if (response.status && response.data) {
        setRecords(response.data.records);
        setLatestRecords(response.data.latestRecords);
      }
    } catch (error) {
      setError("获取健康记录失败");
    } finally {
      setIsLoading(false);
    }
  }

  async function handleCreate() {
    try {
      if (!editingRecord) return;
      const response = await HealthService.createRecord({
        ...editingRecord,
        source: "manual",
      });

      if (response.status && response.data) {
        await fetchHealthRecords();
        setIsCreating(false);
        setEditingRecord(null);
      }
    } catch (error) {
      setModalError(error instanceof Error ? error.message : "创建记录失败");
    }
  }

  async function handleUpdate(recordId: string) {
    try {
      if (!editingRecord) return;
      const response = await HealthService.updateRecord(
        recordId,
        editingRecord
      );
      if (response.status && response.data) {
        await fetchHealthRecords();
        setEditingRecord(null);
      }
    } catch (error) {
      setModalError(error instanceof Error ? error.message : "更新记录失败");
    }
  }

  async function handleDelete(recordId: string) {
    if (!window.confirm("确定要删除这条记录吗？")) return;
    try {
      const response = await HealthService.deleteRecord(recordId);
      if (response.status) {
        await fetchHealthRecords();
      }
    } catch (error) {
      setError("删除记录失败");
    }
  }

  return (
    <AuthGuard>
      <div className="container mx-auto py-8 px-4">
        {/* 页面标题 */}
        <div className="mb-12 text-center">
          <h1 className="text-4xl font-bold mb-4">健康数据</h1>
          <p className="text-muted-foreground text-lg max-w-2xl mx-auto">
            记录和追踪您的健康指标，每一个小进步都是通向健康生活的重要一步 ✨
          </p>
          <div className="mt-6 flex justify-center">
            <button
              onClick={() => setIsCreating(true)}
              className="flex items-center gap-2 bg-primary text-primary-foreground px-6 py-3 rounded-full hover:bg-primary/90 transition-all transform hover:scale-105 shadow-lg"
            >
              <Plus className="w-5 h-5" />
              记录新的健康数据
            </button>
          </div>
        </div>

        {/* 健康数据统计 */}
        <HealthStats 
          latestRecords={latestRecords}
          records={records}
        />

        {/* 健康趋势图表 */}
        <div className="mb-12">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-2xl font-bold">健康趋势</h2>
            <select
              className="text-sm bg-transparent border rounded-lg px-3 py-1.5 pr-8 appearance-none cursor-pointer hover:bg-accent transition-colors"
              onChange={(e) => setActiveChart(e.target.value as HealthRecord['recordType'])}
              value={activeChart}
            >
              <option value="weight">体重趋势</option>
              <option value="bloodPressure">血压趋势</option>
              <option value="heartRate">心率趋势</option>
              <option value="sleepQuality">睡眠趋势</option>
            </select>
          </div>

          <div className="grid grid-cols-1 gap-6">
            {activeChart === "weight" && (
              <HealthTrends
                data={records
                  .filter(r => r.recordType === "weight")
                  .reduce((acc, curr) => {
                    const date = new Date(curr.timestamp).toLocaleDateString();
                    const existing = acc.find(item => 
                      new Date(item.date).toLocaleDateString() === date
                    );
                    
                    if (!existing || new Date(curr.timestamp) > new Date(existing.date)) {
                      if (existing) {
                        existing.date = new Date(curr.timestamp).toISOString();
                        existing.value = curr.details.weight?.value || 0;
                      } else {
                        acc.push({
                          date: new Date(curr.timestamp).toISOString(),
                          value: curr.details.weight?.value || 0
                        });
                      }
                    }
                    return acc;
                  }, [] as { date: string; value: number }[])
                  .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
                  .slice(-30)
                }
                type="weight"
                unit="kg"
              />
            )}
            {activeChart === "heartRate" && (
              <HealthTrends
                data={records
                  .filter(r => {
                    const recordDate = new Date(r.timestamp);
                    const today = new Date();
                    return r.recordType === "heartRate" && 
                      recordDate.getDate() === today.getDate() &&
                      recordDate.getMonth() === today.getMonth() &&
                      recordDate.getFullYear() === today.getFullYear();
                  })
                  .map((r) => ({
                    date: new Date(r.timestamp).toISOString(),
                    value: r.details.heartRate?.current || 0,
                  }))
                  .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
                }
                type="heartRate"
                unit="bpm"
              />
            )}
            {activeChart === "bloodPressure" && (
              <HealthTrends
                data={records
                  .filter(r => r.recordType === "bloodPressure")
                  .reduce((acc, curr) => {
                    const date = new Date(curr.timestamp).toLocaleDateString();
                    const existing = acc.find(item => 
                      new Date(item.date).toLocaleDateString() === date
                    );
                    
                    if (!existing || new Date(curr.timestamp) > new Date(existing.date)) {
                      if (existing) {
                        existing.date = new Date(curr.timestamp).toISOString();
                        existing.value = curr.details.bloodPressure?.systolic || 0;
                        existing.value2 = curr.details.bloodPressure?.diastolic || 0;
                      } else {
                        acc.push({
                          date: new Date(curr.timestamp).toISOString(),
                          value: curr.details.bloodPressure?.systolic || 0,
                          value2: curr.details.bloodPressure?.diastolic || 0
                        });
                      }
                    }
                    return acc;
                  }, [] as { date: string; value: number; value2: number }[])
                  .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
                  .slice(-30)
                }
                type="bloodPressure"
                unit="mmHg"
              />
            )}
            {activeChart === "sleepQuality" && (
              <HealthTrends
                data={records
                  .filter(r => r.recordType === "sleepQuality")
                  .reduce((acc, curr) => {
                    const date = new Date(curr.timestamp).toLocaleDateString();
                    const existing = acc.find(item => 
                      new Date(item.date).toLocaleDateString() === date
                    );
                    
                    if (!existing || new Date(curr.timestamp) > new Date(existing.date)) {
                      if (existing) {
                        existing.date = new Date(curr.timestamp).toISOString();
                        existing.value = curr.details.sleepQuality?.totalSleepDuration || 0;
                      } else {
                        acc.push({
                          date: new Date(curr.timestamp).toISOString(),
                          value: curr.details.sleepQuality?.totalSleepDuration || 0
                        });
                      }
                    }
                    return acc;
                  }, [] as { date: string; value: number }[])
                  .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
                  .slice(-30)
                }
                type="sleepQuality"
                unit="小时"
              />
            )}
          </div>
        </div>

        {/* 健康记录列表 */}
        {isLoading ? (
          <div>加载中...</div>
        ) : error ? (
          <div className="text-destructive">{error}</div>
        ) : (
          <HealthRecordList
            records={records}
            onEdit={setEditingRecord}
            onDelete={handleDelete}
          />
        )}

        {/* 健康小贴士 */}
        <HealthTips />

        {/* 创建/编辑记录表单 */}
        {(isCreating || editingRecord) && (
          <HealthRecordForm
            record={
              editingRecord || {
                recordType: "weight",
                details: {
                  weight: {
                    value: 0,
                    unit: "kg",
                  },
                },
                source: "manual",
                timestamp: new Date(),
              }
            }
            isCreating={isCreating}
            error={modalError}
            onClose={() => {
              setIsCreating(false);
              setEditingRecord(null);
              setModalError("");
            }}
            onChange={(record) => setEditingRecord(record as HealthRecord)}
            onSave={() => {
              if (isCreating) {
                handleCreate();
              } else if (editingRecord) {
                handleUpdate(editingRecord._id);
              }
            }}
            onError={setModalError}
          />
        )}
      </div>
    </AuthGuard>
  );
}
